package com.cjx.gateway.security;

import cn.hutool.core.util.ArrayUtil;
import com.cjx.common.constant.AuthConstant;
import com.cjx.gateway.config.WhiteListConfig;
import com.cjx.gateway.security.handle.MyServerAccessDeniedHandler;
import com.cjx.gateway.security.handle.MyServerAuthenticationEntryPoint;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter;
import org.springframework.security.web.server.SecurityWebFilterChain;
import reactor.core.publisher.Mono;

/**
*@Description 将鉴权管理器AuthorizationManager配置到资源服务器
*@Verson v1.0.0
*@Author cjunxian
*@Date 
*/
@AllArgsConstructor
@Configuration
@EnableWebFluxSecurity
public class ResourceSecurityConfig {

    /**
     * 鉴权管理器
     */
    @Autowired
    private AuthorizationManager authorizationManager;

    /**
     * 白名单配置
     */
    @Autowired
    private WhiteListConfig whiteListConfig;

    /**
     * 自定义未授权响应
     * @param http
     * @return
     */
    @Autowired
    MyServerAccessDeniedHandler myServerAccessDeniedHandler;

    /**
     * 自定义未认证响应
     */
    @Autowired
    MyServerAuthenticationEntryPoint myServerAuthenticationEntryPoint;

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        http.oauth2ResourceServer().jwt()
                .jwtAuthenticationConverter(jwtAuthenticationConverter());
        // 自定义处理JWT请求头过期或签名错误的结果
        http.oauth2ResourceServer().authenticationEntryPoint(myServerAuthenticationEntryPoint);
        http.authorizeExchange()
                .pathMatchers(ArrayUtil.toArray(whiteListConfig.getUrls(),String.class)).permitAll()
                .anyExchange().access(authorizationManager)
                .and()
                .exceptionHandling()
                // 处理未授权
                .accessDeniedHandler(myServerAccessDeniedHandler)
                //处理未认证
                .authenticationEntryPoint(myServerAuthenticationEntryPoint)
                .and().csrf().disable();

        return http.build();
    }

    /**
     * @linkhttps://blog.csdn.net/qq_24230139/article/details/105091273
     * ServerHttpSecurity没有将jwt中authorities的负载部分当做Authentication
     * 需要把jwt的Claim中的authorities加入
     * 方案：重新定义ReactiveAuthenticationManager权限管理器，默认转换器JwtGrantedAuthoritiesConverter
     */
    @Bean
    public Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        //权限补充ROLE_前缀
        jwtGrantedAuthoritiesConverter.setAuthorityPrefix(AuthConstant.ROLE_KEY);
        //jwt负载中存在authorities字段用作保存权限
        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName(AuthConstant.JWT_AUTHORITIES_KEY);

        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
    }
}
